Skip to main content

5. Consume the loader

Picking the right method

We recommend consuming the loader with either withLoader or AwaitLoader.

  • Use withLoader if you want to use the loader to affect the whole component.
  • Use AwaitLoader if you want to use the loader in a more conditional way, or if you only want a small section of your component to start loading data, after the rest of the component has rendered.

You could also use useLoader, which is the hook that withLoader and AwaitLoader use under the hood. This will simply return the aggregated queries of the loader, and is useful if you want to use the data, but not the loading and error states of the loader.

Chart showing differences between AwaitLoader and withLoader

Examples

Select a tab below to see an example of how you would consume the loader using that specific method.

A convenient wrapper that ensures that the component is only rendered when it has data.

info

This is the recommended and optimal way to consume the loaders.

import { withLoader } from "@ryfylke-react/rtk-query-loader";
import { userRouteLoader } from "../loaders/baseLoader";

type Props = {
/* ... */
};

export const UserRoute = withLoader((props: Props, loader) => {
// `queries` is typed correctly, and ensured to have loaded.
const {
user,
posts
} = loader.queries;

return (
<article>
<header>
<h2>{user.data.name}</h2>
{user.isFetching || posts.isFetching ? (<InlineLoading />) : null}
</header>
<main>
{posts.data.map((post) => (...))}
</main>
</article>
);
}, userRouteLoader);